<template>
  <div class="edit">
    <!-- 头部导航结构 -->
    <van-nav-bar
      title="用户编辑页"
      left-arrow
      @click-left="$router.back()"
      @click-right="$router.push({ path: '/' })"
    >
      <template #right>
        <van-icon name="wap-home-o" size="5vw" />
      </template>
    </van-nav-bar>
    <!-- 2.0头像 -->
    <div class="avatar">
      <div class="avatar-img">
        <van-uploader :after-read="afterRead">
          <van-image
            round
            fit="cover"
            width="100%"
            height="100%"
            :src="userinfo.head_img"
        /></van-uploader>
      </div>
    </div>
    <!-- 3.0 单元格 -->
    <!-- @click 点击事件其实可以写多行代码，用分号; 隔开即可 -->
    <MyCell
      title="昵称"
      :value="userinfo.nickname"
      @click="
        nicknameShow = true;
        nicknameTemp = userinfo.nickname;
      "
    ></MyCell>
    <MyCell
      title="密码"
      value="******"
      @click="
        passwordShow = true;
        passwordOld = '';
        passwordNew = '';
        eye = true;
        eye2 = true;
      "
    ></MyCell>
    <MyCell
      title="性别"
      :value="userinfo.gender ? '男' : '女'"
      @click="genderShow = true"
    ></MyCell>
    <!-- 弹出框 -->
    <div>
      <!-- van dialog 组件用法 -->
      <van-dialog
        v-model="nicknameShow"
        title="编辑昵称"
        show-cancel-button
        @confirm="nicknameFn"
      >
        <van-field
          required
          v-model="nicknameTemp"
          label="文本"
          placeholder="请输入用户名"
          clearable
        />
      </van-dialog>
      <!-- 修改密码的模态框 -->
      <van-dialog
        v-model="passwordShow"
        title="修改密码"
        show-cancel-button
        :before-close="beforeClose"
      >
        <van-field
          required
          v-model="passwordOld"
          label="原密码"
          :type="posswordOldType ? 'password' : 'txt'"
          placeholder="请输入原密码"
          clearable
        >
          <template #button>
            <div
              @click="
                eye = !eye;
                posswordOldType = !posswordOldType;
              "
            >
              <van-icon name="closed-eye" size="5vw" v-if="eye" />
              <van-icon name="eye-o" size="5vw" v-else />
            </div>
          </template>
        </van-field>
        <van-field
          required
          v-model="passwordNew"
          label="新密码"
          placeholder="请输入新密码"
          :type="posswordNewType ? 'password' : 'txt'"
          clearable
        >
          <template #button>
            <div
              @click="
                eye2 = !eye2;
                posswordNewType = !posswordNewType;
              "
            >
              <van-icon name="closed-eye" size="5vw" v-if="eye2" />
              <van-icon name="eye-o" size="5vw" v-else />
            </div>
          </template>
        </van-field>
      </van-dialog>
      <!--  用户性别修改模态框 -->

      <van-action-sheet
        v-model="genderShow"
        :actions="actions"
        cancel-text="取消"
        close-on-click-action
        @select="genderFn"
      />
    </div>
  </div>
</template>

<script>
//this.$router.back() 可以返回
import MyCell from "../components/MyCell.vue";
import { getUserInfoAPI, userUpdateByIdAPI } from "../apis/user";
import axios from "../utils/request";
import { uploadFileAPI } from "../apis/index";

export default {
  components: {
    MyCell,
  },
  data() {
    return {
      userinfo: {},
      nicknameShow: false,
      nicknameTemp: "",
      passwordShow: false,
      passwordOld: "",
      passwordNew: "",
      eye: true,
      posswordOldType: true,
      eye2: true,
      posswordNewType: true,
      genderShow: false,
      actions: [
        { name: "男", gender: 1 },
        { name: "女", gender: 0 },
      ],
    };
  },
  async created() {
    // 通过 Vue 调试工具可以更方便找到 id 到底是在那个对象上存储
    const id = this.$route.query.id;
    // 根据 id 获取用户信息
    const res = await getUserInfoAPI(id);
    // console.log(res);
    //渲染前补全头像地址
    // 💥 检查是否获取到数据
    if (res.data.data) {
      res.data.data.head_img = axios.defaults.baseURL + res.data.data.head_img;
      // 把处理后的数据绑定到 data 中，再用于页面展示
      this.userinfo = res.data.data;
    }
    // console.log(this.userinfo);
  },
  methods: {
    async afterRead(file) {
      // 此时可以自行将文件上传至服务器
      //   console.log(file);
      // 上传需要用 FormData 的方式
      const fd = new FormData();
      fd.append("file", file.file);
      //   console.log(file.file);
      // 传进入的参数是一个 FormData 对象
      const res = await uploadFileAPI(fd);
      //   console.log(res);
      if (res.data.message === "文件上传成功") {
        const imgUrl = res.data.data.url;
        // console.log(imgUrl);
        // 把新的图片地址，更新到用户信息中
        const res2 = await userUpdateByIdAPI(this.$route.query.id, {
          head_img: imgUrl,
        });
        // console.log(res2);
        // 更新头像的展示
        this.userinfo.head_img =
          axios.defaults.baseURL + res2.data.data.head_img;
        this.$toast.success("头像更新成功");
      }
    },
    async nicknameFn() {
      //   console.log(this.nicknameTemp);
      if (this.nicknameTemp === "") return this.$notify("请输入昵称，不能为空");
      // 发送请求更新用户昵称
      const res = await userUpdateByIdAPI(this.$route.query.id, {
        nickname: this.nicknameTemp,
      });
      //   console.log(res);
      this.userinfo.nickname = res.data.data.nickname;
      this.$toast.success("昵称修改成功");
    },
    // 修改密码
    // 关闭密码弹出框前执行的函数
    async beforeClose(action, done) {
      // console.log(action);

      if (action === "confirm") {
        // 判断用户输入的密码是否正确
        if (
          this.passwordOld !== this.userinfo.password ||
          !/^[a-zA-Z0-9~!@#$%^&*_+=-]{3,18}$/.test(this.passwordNew)
        ) {
          this.$toast.fail("输入的原密码错误了或者新密码格式不正确~~");
          // 调用 done(false) 阻止弹窗关闭
          done(false);
        } else {
          const res = await userUpdateByIdAPI(this.$route.query.id, {
            password: this.passwordNew,
          });
          // console.log(res);
          if (res.data.message === "修改成功") {
            this.userinfo.password = this.passwordNew;
            this.$toast.success("密码修改成功");
          }
          done();
        }
      } else {
        // 调用 done() 后关闭弹窗，
        done();
      }
    },
    // 用户性别修改
    async genderFn(item) {
      console.log("你点击了", item);
      const res = await userUpdateByIdAPI(this.$route.query.id, {
        gender: item.gender,
      });
      // console.log(res);
      if (res.data.message === "修改成功") {
        this.userinfo.gender = res.data.data.gender;
        this.$toast.success("性别修改成功");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.avatar {
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #eee;
  .avatar-img {
    width: 100px;
    height: 100px;
  }
}
</style>